package ch16 {
	/**
	 * 创建 3D 填充，3D 圆筒
	 * 移动三维立体模型
	 * 运用三角形,渲染图形
	 * @author jianping.shenjp
	 */
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import utils.Point3D;
	import utils.Triangle;

	public class Cylinder extends Sprite {
		private var points:Array;
		private var triangles:Array;
		private var fl:Number = 250;
		private var vpX:Number = stage.stageWidth / 2;
		private var vpY:Number = stage.stageHeight / 2;
		private var numFaces:uint = 20;
		private var numchild:int = 0;
		private var offsetX:Number = 0.0;
		private var offsetY:Number = 0.0;

		public function Cylinder(){
			init();
		}

		private function init():void {
			points = new Array();
			triangles = new Array();
			var index:uint = 0;
			var numchild:int = 0;
			var tempAngle:Number = Math.PI * 2 / numFaces;
			for (var i:uint = 0; i < numFaces; i++){
				var angle:Number = tempAngle * i;
				var xpos:Number = Math.cos(angle) * 200;
				var ypos:Number = Math.sin(angle) * 200;
				points[index] = new Point3D(xpos, ypos, -100);
				points[index + 1] = new Point3D(xpos, ypos, 100);
				index += 2;
			}
			numchild = points.length;
			for (i = 0; i < numchild; i++){
				points[i].setVanishingPoint(vpX, vpY);
				points[i].setCenter(0, 0, 200);
			}
			index = 0;
			for (i = 0; i < numFaces - 1; i++){
				triangles[index] = new Triangle(points[index], points[index + 3], points[index + 1], 0x6666cc);
				triangles[index + 1] = new Triangle(points[index], points[index + 2], points[index + 3], 0x6666cc);
				index += 2;
			}
			triangles[index] = new Triangle(points[index], points[1], points[index + 1], 0x6666cc);
			triangles[index + 1] = new Triangle(points[index], points[0], points[1], 0x6666cc);
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
		}

		private function onKeyDown(event:KeyboardEvent):void {
			if (event.keyCode == Keyboard.LEFT){
				offsetX -= 5;
			} else if (event.keyCode == Keyboard.RIGHT){
				offsetX += 5;
			} else if (event.keyCode == Keyboard.UP){
				offsetY -= 5;
			} else if (event.keyCode == Keyboard.DOWN){
				offsetY += 5;
			}
			numchild = points.length;
			for (var i:Number = 0; i < numchild; i++){
				points[i].setCenter(offsetX, offsetY, 200);
			}
		}

		private function onEnterFrame(event:Event):void {
			var angleX:Number = (mouseY - vpY) * .001;
			var angleY:Number = (mouseX - vpX) * .001;
			numchild = points.length;
			for (var i:uint = 0; i < numchild; i++){
				var point:Point3D = points[i];
				point.rotateX(angleX);
				point.rotateY(angleY);
			}
			graphics.clear();
			for (i = 0; i < triangles.length; i++){
				triangles[i].draw(graphics);
			}
		}
	}

}